<template>
    <div>
        <el-dialog v-model="props.brandVisible" :title="newTitle" width="500" :before-close="handleBrandVisibleClose">
            <el-form :model="AddBrandFrom" label-width="auto" ref="AddCategoryRef" label-position="top"
                :rules="rulesList">
                <el-form-item label="图片" prop="newImage" required>
                    <ImageUpload :limit="1" v-model="AddBrandFrom.newImage" @baseUrl="handleImageList"></ImageUpload>
                </el-form-item>
                <el-form-item label="商品类型" prop="recordValue" required>
                    <el-space spacer=" ">
                        <el-text>{{ menuTypeAssociationIdFrom?.name || '请选择' }}</el-text>
                        <el-button type="primary" @click="addListId">新增</el-button>
                    </el-space>
                </el-form-item>


                <el-form-item label="链接" prop="url">
                    <el-input v-model.trim="AddBrandFrom.url" placeholder="请输入"
                        :disabled="AddBrandFrom.sysTagType != 'link'">
                    </el-input>
                </el-form-item>
                <el-form-item prop="titleGroups">
                    <MoreLanguage :newList="AddBrandFrom.titleGroups" label="主题名称" :showRemark="true"
                        :showControls="true">
                    </MoreLanguage>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleBrandVisibleClose">取消</el-button>
                    <el-button type="primary" @click="handleBrandVisibleSure(AddCategoryRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <PublicList :from="menuTypeAssociationIdFrom" newType="category" @publicListSure="publicListSure"
            @publicListCancel="publicListCancel" :showList="showList" :websiteId="props.websiteId"
            :languageId="props.languageId">
        </PublicList>
    </div>
</template>
<script setup scoped>
import { ref, defineProps, defineEmits, watch, onMounted } from "vue";
import { slugify } from "transliteration";
import PublicList from "./publicList.vue";
const emits = defineEmits([
    "handleBrandVisibleClose",
    "handleBrandVisibleSure",
]);
const { proxy } = getCurrentInstance();
const { sys_tag_type } = proxy.useDict("sys_tag_type");
const AddCategoryRef = ref();
const newTitle = ref("新增"); //名称

const menuTypeAssociationIdFrom = ref({}); //公共赋值数据
const showList = ref(false)//默认不显示，列表弹出框显示
const siteProductSortList = ref([])//商品分类


const AddBrandFrom = ref({
    moduleId: null,
    image: "",
    url: "",
    newImage: "",
    sysTagType: 'category',
    recordValue: null,//选择的id
    titleGroups: [
        // languageId:null,//语言
        // name:null,//标题
        // description:null,//描述
    ],
});

const props = defineProps({
    brandVisible: {
        type: Boolean,
        default: false,
    },
    // 传值数据对象
    listItem: {
        type: Object,
        default: {},
    },
    websiteId: {
        type: String || Number,
        default: "",
    },
    moduleId: {
        type: Number,
        default: null,
    },
    languageId: {
        type: String || Number,
        default: "",
    }
});
watch(
    () => props.brandVisible,
    () => {
        if (!props.brandVisible) return;

        if (Object.keys(props.listItem).length) {
            newTitle.value = "编辑";
            getDetails();
        } else {
            getBasics();
            newTitle.value = "新增";
            proxy.resetForm("AddCategoryRef");
        }
    }
);
const handleBrandVisibleSure = () => {
    proxy.$refs["AddCategoryRef"].validate((valid) => {
        if (!valid) return;
        if (!proxy.publicArray(AddBrandFrom.value.titleGroups))
            return proxy.$modal.msgError("请完整填写多语言");
        AddBrandFrom.value.moduleId = props.moduleId;

        if (newTitle.value === "新增") {
            site.moduleline
                .sitewebsitemodulelineAdd({
                    data: AddBrandFrom.value,
                })
                .then((res) => {
                    if (res.code === 200) {
                        publicReset()
                        emits("handleBrandVisibleSure");
                        proxy.$message.success("新增成功");
                    }
                });
        } else {
            site.moduleline
                .sitewebsitemodulelineUpdate({
                    pathParams: {
                        id: props.listItem.id,
                    },
                    data: AddBrandFrom.value,
                })
                .then((res) => {
                    if (res.code === 200) {
                        publicReset()
                        emits("handleBrandVisibleSure");
                        proxy.$message.success("编辑成功");
                    }
                });
        }
    });
};
const getDetails = () => {
    site.moduleline
        .sitewebsitemodulelineGetbyid({
            pathParams: {
                id: props.listItem.id,
            },
        })
        .then((res) => {
            AddBrandFrom.value.titleGroups = [];
            AddBrandFrom.value.image = res.data.image;
            AddBrandFrom.value.newImage = res.data.host;
            AddBrandFrom.value.sysTagType = res.data.sysTagType;
            detailsTree( Number(res.data.recordValue))
            AddBrandFrom.value.url = res.data.url
            res.data.moduleDescriptions.forEach((e) => {
                AddBrandFrom.value.titleGroups.push({
                    languageId: e.languageId,
                    name: e.name,
                    description: e.description,
                });
            });
        });
};

const getBasics = () => {
    site.general
        .sitewebsiteGetbyid({
            pathParams: {
                id: Number(props.websiteId),
            },
        })
        .then((res) => {
            AddBrandFrom.value.titleGroups = [];
            res.data.languageIds.forEach((e) => {
                AddBrandFrom.value.titleGroups.push({
                    languageId: e,
                    name: "",
                    description: "",
                });
            });
            console.log(res.data.languageIds, "[[[]]]");
        });
};
onMounted(() => {
    getList()
})
const getList = () => {
    site.general
        .sitecategoryList({
            data: {
                pageNum: 1,
                pageSize: 999,
                param: {
                    websiteId: Number(props.websiteId),
                    languageId: Number(props.languageId),
                    fatherId: 0,
                }
            },
        })
        .then((res) => {//商品分类
            siteProductSortList.value = res.data;
        });
}
const rulesList = {
    newImage: [{ required: true, message: "请选择", trigger: "blur" }],
    recordValue: [{ required: true, message: "请选择", trigger: "blur" }],
};
const handleBrandVisibleClose = () => {
    publicReset()
    emits("handleBrandVisibleClose");
};
const handleImageList = (list) => {
    AddBrandFrom.value.image = list.url;
};

const publicListSure = (row) => {//确定事件，进行url处理赋值
    showList.value = false
    menuTypeAssociationIdFrom.value = row
    AddBrandFrom.value.recordValue = row.id
    changeTree(row.id)
}
const changeTree = (e) => {
    const { elTagClass, value } = sys_tag_type.value.find(
        (e) => e.value === 'category'
    )
    const { name, id } = findNodeById(siteProductSortList.value, e)
    AddBrandFrom.value.url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
}
const detailsTree = ( e) => {
    menuTypeAssociationIdFrom.value = findNodeById(siteProductSortList.value, e)
}
function formatUrl(input) {
    return slugify(input, { separator: '-' });
}
const publicListCancel = () => {
    showList.value = false
}
const addListId = () => {
    showList.value = true
}
const findNodeById = (tree, id) => {
    for (let node of tree) {
        if (node.id === id) {
            return node; // 找到目标节点
        }
        if (node.children) {
            let found = findNodeById(node.children, id);
            if (found) return found; // 递归查找子节点
        }
    }
    return null; // 没找到
}
const publicReset = () => {
    proxy.resetForm("AddCategoryRef");
    AddBrandFrom.value.titleGroups = [];
    menuTypeAssociationIdFrom.value = {}
    AddBrandFrom.value.sysTagType = "category"
}
</script>